package ace.cmp.security.oauth2.resource.server.core.service.impl;

import ace.cmp.security.core.impl.service.impl.AbstractSpringSecurityService;
import ace.cmp.security.oauth2.resource.server.core.service.Oauth2SecurityService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;

/**
 * @author caspar
 * @date 2023/9/1 15:12
 */
public class Oauth2ResourceServerSpringSecurityService
    extends AbstractSpringSecurityService<BearerTokenAuthentication>
    implements Oauth2SecurityService {

  private final Oauth2ResourceServerSecurityServiceLoginSupplier loginSupplier;

  public Oauth2ResourceServerSpringSecurityService(Oauth2ResourceServerSecurityServiceLoginSupplier loginSupplier) {
    this.loginSupplier = loginSupplier;
  }

  public Oauth2ResourceServerSpringSecurityService(Oauth2ResourceServerSecurityServiceLoginSupplier loginSupplier,
      String rolePrefix,
      String administratorRoleKeySuffix
  ) {
    super(rolePrefix, administratorRoleKeySuffix);
    this.loginSupplier = loginSupplier;
  }

  @Override
  public Authentication login() {
    return loginSupplier.get();
  }

  @Override
  public Authentication login(BearerTokenAuthentication authentication) {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    return authentication;
  }

  @Override
  public Authentication getAuthentication() {
    return SecurityContextHolder.getContext().getAuthentication();
  }
}
